import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import api from '../../services/api';
import './SocialPage.css';

function SocialPage({ user, token }) {
    const navigate = useNavigate();
    const [posts, setPosts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [message, setMessage] = useState({ type: '', text: '' });
    const [selectedPost, setSelectedPost] = useState(null);
    const [showCreatePost, setShowCreatePost] = useState(false);
    const [likedPosts, setLikedPosts] = useState(new Set());

    // 从user对象中正确提取token
    const getActualToken = () => {
        // 优先使用传入的token参数
        if (token) {
            return token;
        }
        // 如果没有token参数，尝试从user对象中提取
        if (user && user.data && user.data.token) {
            return user.data.token;
        }
        // 如果user对象直接包含token字段
        if (user && user.token) {
            return user.token;
        }
        // 最后尝试从localStorage获取
        return localStorage.getItem('token');
    };

    useEffect(() => {
        fetchPosts();
    }, []);

    // 帖子排序函数：置顶帖子在前，其他按创建时间排序
    const sortPosts = (postsArray) => {
        return postsArray.sort((a, b) => {
            // 首先按是否置顶排序
            if (a.isSticky && !b.isSticky) {
                return -1; // a置顶，a在前
            }
            if (!a.isSticky && b.isSticky) {
                return 1; // b置顶，b在前
            }

            // 如果都是置顶或都不是置顶，按创建时间倒序排序（新的在前）
            const dateA = new Date(a.createTime);
            const dateB = new Date(b.createTime);
            return dateB - dateA;
        });
    };

    const fetchPosts = async () => {
        try {
            setLoading(true);

            const actualToken = getActualToken();

            console.log('=== SocialPage fetchPosts 调试 ===');
            console.log('传入的token参数:', token);
            console.log('user对象:', user);
            console.log('user.data.token:', user?.data?.token);
            console.log('实际使用的token:', actualToken);
            console.log('实际token类型:', typeof actualToken);
            console.log('实际token长度:', actualToken?.length);
            console.log('实际token前20字符:', actualToken?.substring(0, 20));

            // 使用实际提取的token
            const result = await api.getPosts(actualToken);

            // 根据API文档，数据可能在result.records中
            let postsData = result.records || result.data || result;
            postsData = Array.isArray(postsData) ? postsData : [];

            // 对帖子进行排序：置顶帖子在前
            const sortedPosts = sortPosts(postsData);
            console.log('=== 帖子排序结果 ===');
            console.log('置顶帖子数量:', sortedPosts.filter(post => post.isSticky).length);
            console.log('普通帖子数量:', sortedPosts.filter(post => !post.isSticky).length);

            setPosts(sortedPosts);

            // 如果用户已登录，检查点赞状态
            if (user && actualToken && Array.isArray(sortedPosts)) {
                checkLikedPosts(sortedPosts, actualToken);
            }
        } catch (error) {
            console.error('获取帖子列表失败:', error);
            setMessage({ type: 'error', text: '获取帖子列表失败' });
        } finally {
            setLoading(false);
        }
    };

    const checkLikedPosts = async (postsData, actualToken) => {
        const liked = new Set();
        for (const post of postsData) {
            try {
                // 使用实际用户ID
                const actualUserId = user?.data?.id || user?.id;
                const isLiked = await api.hasLiked(actualToken, post.id, actualUserId);
                if (isLiked) {
                    liked.add(post.id);
                }
            } catch (error) {
                console.error('检查点赞状态失败:', error);
            }
        }
        setLikedPosts(liked);
    };

    const handleLike = async (postId) => {
        const actualToken = getActualToken();
        const actualUserId = user?.data?.id || user?.id;

        if (!user || !actualToken) {
            setMessage({ type: 'error', text: '请先登录' });
            setTimeout(() => navigate('/login'), 2000);
            return;
        }

        try {
            const isCurrentlyLiked = likedPosts.has(postId);

            if (isCurrentlyLiked) {
                await api.unlikePost(actualToken, postId, actualUserId);
                setLikedPosts(prev => {
                    const newSet = new Set(prev);
                    newSet.delete(postId);
                    return newSet;
                });
            } else {
                await api.likePost(actualToken, postId, actualUserId);
                setLikedPosts(prev => new Set([...prev, postId]));
            }

            // 更新帖子列表中的点赞数
            setPosts(prev => prev.map(post =>
                post.id === postId
                    ? {
                        ...post,
                        likeCount: isCurrentlyLiked
                            ? (post.likeCount || 1) - 1
                            : (post.likeCount || 0) + 1
                    }
                    : post
            ));
        } catch (error) {
            console.error('点赞操作失败:', error);
            setMessage({ type: 'error', text: '点赞操作失败' });
        }
    };

    const formatDate = (dateString) => {
        const date = new Date(dateString);
        const now = new Date();
        const diffTime = Math.abs(now - date);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        if (diffDays === 1) {
            return '今天';
        } else if (diffDays === 2) {
            return '昨天';
        } else if (diffDays <= 7) {
            return `${diffDays - 1}天前`;
        } else {
            return date.toLocaleDateString('zh-CN');
        }
    };

    if (loading) {
        return (
            <div className="social-container">
                <div className="loading">加载中...</div>
            </div>
        );
    }

    return (
        <div className="social-container">
            {/* 头部操作栏 */}
            <div className="social-header">
                <div className="social-title">
                    <h1>💬 社交广场</h1>
                    <p>与大家分享你的想法和发现</p>
                </div>
                {user && (
                    <button
                        onClick={() => setShowCreatePost(true)}
                        className="create-post-btn"
                    >
                        ✍️ 发布帖子
                    </button>
                )}
            </div>

            {message.text && (
                <div className={`message ${message.type}`}>
                    {message.text}
                </div>
            )}

            {/* 帖子列表 */}
            <div className="posts-container">
                {posts.length === 0 ? (
                    <div className="empty-posts">
                        <div className="empty-icon">📝</div>
                        <p>还没有帖子，来发布第一个帖子吧！</p>
                    </div>
                ) : (
                    posts.map(post => (
                        <div key={post.id} className={`post-card ${post.isSticky ? 'sticky-post' : ''}`}>
                            {/* 置顶标识 */}
                            {post.isSticky && (
                                <div className="sticky-badge">
                                    📌 置顶
                                </div>
                            )}

                            <div className="post-header">
                                <div className="post-author">
                                    <div className="author-avatar">👤</div>
                                    <div className="author-info">
                                        <div className="author-name">
                                            用户 {post.userId}
                                            {post.isSticky && (
                                                <span className="sticky-indicator">🔥</span>
                                            )}
                                        </div>
                                        <div className="post-time">{formatDate(post.createTime)}</div>
                                    </div>
                                </div>
                            </div>

                            <div className="post-content">
                                <h3 className="post-title">
                                    {post.title}
                                    {post.isSticky && (
                                        <span className="sticky-title-indicator">📌</span>
                                    )}
                                </h3>
                                <div className="post-text">
                                    {post.content.length > 200
                                        ? `${post.content.substring(0, 200)}...`
                                        : post.content
                                    }
                                </div>
                            </div>

                            <div className="post-actions">
                                <button
                                    onClick={() => handleLike(post.id)}
                                    className={`action-btn like-btn ${likedPosts.has(post.id) ? 'liked' : ''}`}
                                    disabled={!user}
                                >
                                    {likedPosts.has(post.id) ? '❤️' : '🤍'} {post.likeCount || 0}
                                </button>

                                <button
                                    onClick={() => setSelectedPost(post)}
                                    className="action-btn comment-btn"
                                >
                                    💬 {post.commentCount || 0}
                                </button>

                                <button
                                    onClick={() => setSelectedPost(post)}
                                    className="action-btn detail-btn"
                                >
                                    查看详情
                                </button>
                            </div>
                        </div>
                    ))
                )}
            </div>

            {/* 创建帖子弹窗 */}
            {showCreatePost && (
                <CreatePostModal
                    user={user}
                    token={getActualToken()}
                    onClose={() => setShowCreatePost(false)}
                    onSuccess={() => {
                        setShowCreatePost(false);
                        fetchPosts();
                        setMessage({ type: 'success', text: '帖子发布成功！' });
                    }}
                />
            )}

            {/* 帖子详情弹窗 */}
            {selectedPost && (
                <PostDetailModal
                    post={selectedPost}
                    user={user}
                    token={getActualToken()}
                    isLiked={likedPosts.has(selectedPost.id)}
                    onClose={() => setSelectedPost(null)}
                    onLike={() => handleLike(selectedPost.id)}
                    onCommentAdded={fetchPosts}
                />
            )}
        </div>
    );
}

// 创建帖子弹窗组件
function CreatePostModal({ user, token, onClose, onSuccess }) {
    const [formData, setFormData] = useState({
        title: '',
        content: '',
        userId: user?.data?.id || user?.id
    });
    const [loading, setLoading] = useState(false);
    const [message, setMessage] = useState({ type: '', text: '' });

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!formData.title.trim() || !formData.content.trim()) {
            setMessage({ type: 'error', text: '请填写标题和内容' });
            return;
        }

        setLoading(true);
        try {
            await api.createPost(token, formData);
            onSuccess();
        } catch (error) {
            setMessage({ type: 'error', text: error.message || '发布失败' });
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={e => e.stopPropagation()}>
                <div className="modal-header">
                    <h2>✍️ 发布新帖子</h2>
                    <button className="modal-close" onClick={onClose}>✕</button>
                </div>

                {message.text && (
                    <div className={`message ${message.type}`}>
                        {message.text}
                    </div>
                )}

                <form onSubmit={handleSubmit} className="create-post-form">
                    <div className="form-group">
                        <label className="form-label">📝 标题</label>
                        <input
                            type="text"
                            name="title"
                            value={formData.title}
                            onChange={handleInputChange}
                            className="form-input"
                            placeholder="给你的帖子起个标题..."
                            maxLength={100}
                            required
                        />
                        <div className="char-count">{formData.title.length}/100</div>
                    </div>

                    <div className="form-group">
                        <label className="form-label">📄 内容</label>
                        <textarea
                            name="content"
                            value={formData.content}
                            onChange={handleInputChange}
                            className="form-textarea"
                            placeholder="分享你的想法..."
                            rows={8}
                            maxLength={2000}
                            required
                        />
                        <div className="char-count">{formData.content.length}/2000</div>
                    </div>

                    <div className="modal-actions">
                        <button
                            type="button"
                            onClick={onClose}
                            className="btn btn-secondary"
                        >
                            取消
                        </button>
                        <button
                            type="submit"
                            disabled={loading}
                            className="btn"
                        >
                            {loading ? '发布中...' : '发布帖子'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}

// 帖子详情弹窗组件 - 添加置顶显示
function PostDetailModal({ post, user, token, isLiked, onClose, onLike, onCommentAdded }) {
    const [comments, setComments] = useState([]);
    const [newComment, setNewComment] = useState('');
    const [commentsLoading, setCommentsLoading] = useState(true);
    const [commentLoading, setCommentLoading] = useState(false);
    const [message, setMessage] = useState({ type: '', text: '' });

    useEffect(() => {
        fetchComments();
    }, [post.id]);

    const fetchComments = async () => {
        try {
            setCommentsLoading(true);
            const result = await api.getComments(token, post.id);
            const commentsData = result.records || result.data || result;
            setComments(Array.isArray(commentsData) ? commentsData : []);
        } catch (error) {
            console.error('获取评论失败:', error);
            setMessage({ type: 'error', text: '获取评论失败' });
        } finally {
            setCommentsLoading(false);
        }
    };

    const handleAddComment = async (e) => {
        e.preventDefault();
        if (!user || !token) {
            setMessage({ type: 'error', text: '请先登录' });
            return;
        }
        if (!newComment.trim()) {
            setMessage({ type: 'error', text: '请输入评论内容' });
            return;
        }

        setCommentLoading(true);
        try {
            const commentData = {
                postId: post.id,
                userId: user?.data?.id || user?.id,
                content: newComment.trim()
            };

            await api.createComment(token, commentData);
            setNewComment('');
            fetchComments();
            onCommentAdded();
            setMessage({ type: 'success', text: '评论发表成功！' });
        } catch (error) {
            setMessage({ type: 'error', text: error.message || '发表评论失败' });
        } finally {
            setCommentLoading(false);
        }
    };

    const formatDate = (dateString) => {
        return new Date(dateString).toLocaleString('zh-CN');
    };

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className={`modal-content large ${post.isSticky ? 'sticky-modal' : ''}`} onClick={e => e.stopPropagation()}>
                <div className="modal-header">
                    <h2>
                        📄 帖子详情
                        {post.isSticky && (
                            <span className="sticky-modal-badge">📌 置顶</span>
                        )}
                    </h2>
                    <button className="modal-close" onClick={onClose}>✕</button>
                </div>

                {message.text && (
                    <div className={`message ${message.type}`}>
                        {message.text}
                    </div>
                )}

                <div className="post-detail">
                    <div className="post-detail-header">
                        <div className="post-author">
                            <div className="author-avatar">👤</div>
                            <div className="author-info">
                                <div className="author-name">
                                    用户 {post.userId}
                                    {post.isSticky && (
                                        <span className="sticky-indicator">🔥</span>
                                    )}
                                </div>
                                <div className="post-time">{formatDate(post.createTime)}</div>
                            </div>
                        </div>
                    </div>

                    <div className="post-detail-content">
                        <h1 className="post-detail-title">
                            {post.title}
                            {post.isSticky && (
                                <span className="sticky-title-indicator-large">📌</span>
                            )}
                        </h1>
                        <div className="post-detail-text">{post.content}</div>
                    </div>

                    <div className="post-detail-actions">
                        <button
                            onClick={onLike}
                            className={`action-btn like-btn ${isLiked ? 'liked' : ''}`}
                            disabled={!user}
                        >
                            {isLiked ? '❤️' : '🤍'} {post.likeCount || 0}
                        </button>
                        <span className="action-btn comment-count">
                            💬 {comments.length}
                        </span>
                    </div>
                </div>

                <div className="comments-section">
                    <h3>💬 评论 ({comments.length})</h3>

                    {user && (
                        <form onSubmit={handleAddComment} className="comment-form">
                            <textarea
                                value={newComment}
                                onChange={(e) => setNewComment(e.target.value)}
                                className="comment-input"
                                placeholder="发表你的看法..."
                                rows={3}
                                maxLength={500}
                            />
                            <div className="comment-form-actions">
                                <div className="char-count">{newComment.length}/500</div>
                                <button
                                    type="submit"
                                    disabled={commentLoading || !newComment.trim()}
                                    className="btn btn-sm"
                                >
                                    {commentLoading ? '发表中...' : '发表评论'}
                                </button>
                            </div>
                        </form>
                    )}

                    <div className="comments-list">
                        {commentsLoading ? (
                            <div className="loading">加载评论中...</div>
                        ) : comments.length === 0 ? (
                            <div className="empty-comments">
                                暂无评论，来发表第一个评论吧！
                            </div>
                        ) : (
                            comments.map(comment => (
                                <div key={comment.id} className="comment-item">
                                    <div className="comment-author">
                                        <div className="comment-avatar">👤</div>
                                        <div className="comment-info">
                                            <div className="comment-author-name">用户 {comment.userId}</div>
                                            <div className="comment-time">{formatDate(comment.createTime)}</div>
                                        </div>
                                    </div>
                                    <div className="comment-content">{comment.content}</div>
                                </div>
                            ))
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}

export default SocialPage;